/**
 * Created by Administrator on 2017/3/21.
 */
import React, {Component, Fragment} from 'react';
import {Form, Input, DatePicker, message, Button, Tabs, Alert, Table, Col, Row, Badge, Modal} from 'antd';
import {connect} from 'dva';
import L from 'leaflet';   //引入leaflet
import MyPagination from '@/components/MyPagination';
import './index.less';
import './../Home/leaflet.less';
import Template2 from './Template2';
import {afterCloseModal, getTimeDistance, timeStamp} from '@/utils/utils';
import ReactDataGrid from 'react-data-grid';
import forEach from 'lodash/forEach';
import moment from 'moment';
import request from '@/utils/request';
import ReactEcharts from 'echarts-for-react';
import ValveHistoryData from "@/pages/ValveFlowMeterSIte/ValveHistoryData";
import BuildModalTitle from "@/components/BuildModalTitle";
import find from "lodash/find";
const { TabPane } = Tabs;
const ButtonGroup = Button.Group;

class AddPoliciesForm extends Component {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      color:'#fff',
      type:'modbus',
      name:'',
      renderName:'',
      channel:0,
      showType: 1,
      historyData: [],
      config_data: {
        modbus: [{}]
      },
      start_date: moment().format('YYYY-MM-DD'),
      end_date: moment().format('YYYY-MM-DD'),
      isWatch: false,
      tabPanes: [{
        name: '设备信息',
        key: 'device',
      }, {
        name: '通道2液位',
        key: 'sensor_1',
      }],
      device_0: {
        meta: {total: 0, per_page: 0, current_page: 1},
        data: [],
        loading: false,
      },
      sensor_1: {
        meta: {total: 0, per_page: 0, current_page: 1},
        data: [],
        loading: false,
      },
      sensor_1_chart: {
        meta: {total: 0, per_page: 0, current_page: 1},
        data: [], loading: false,
      },
    };
  }

  componentDidMount() {
    const that = this;
    this.fetchBaseInfo();
    this.fetch({
      type: 'sensor',
      channel: 1,
      page: 1,
      per_page: 20,
    });

    this.fetch({
      type: 'device',
      channel: 0,
      page: 1,
      per_page: 20,
    });
    that.fetSensors()
    this.timer = setInterval(function () {
      that.fetSensors();
      // that.fetHistory();
      // that.fetchBaseInfo();
    }, 15000)

  }

  fetchBaseInfo = () => {
    const that = this;
    request(`/workstations/${this.props.editRecord.id}`, {
      method: 'GET',
      params: {},
    }).then((response) => {
      if (response.status === 200) {
        console.log('response', response);
        this.setState({
          config_data: response.data.data.hardware_configs,
          isWatch: response.data.data.is_watch
        });
      }
    });
  }
  openWatch = () => {
    const that = this;
    request(`/workstations/${this.props.editRecord.id}/watch_mode`, {
      method: 'PUT',
    }).then(response => {
      if (response.status === 200) {
        message.success('开启监控模式成功')
        that.fetchBaseInfo()

      }
    });
  }

  componentWillUnmount() {
    if (this.timer) {
      clearInterval(this.timer)
    }
  }

  fetSensors = () => {
    this.fetchChart({
      type: 'sensor',
      channel: 1,
      page: 1,
      per_page: 20,
    });
  }

  selectDate = (type) => {
    const that = this;
    this.setState({
      rangePickerValue: getTimeDistance(type),
    }, function () {
      // that.fetch();
    });


  };
  fetch = (params) => {
    const that = this;
    this.setState({
      [`${params.type}_${params.channel}`]: {
        meta: this.state[`${params.type}_${params.channel}`].meta,
        data: this.state[`${params.type}_${params.channel}`].data,
        loading: true,
      },
    });

    request(`/workstation_historical_data`, {
      method: 'GET',
      params: {
        ...params,
        start_date: this.state.start_date,
        end_date: this.state.end_date,
        workstation_id: this.props.editRecord.id,
        order_direction: 'desc'
      },
    }).then(response => {
      if (response.status === 200) {
        that.setState({
          [`${params.type}_${params.channel}`]: {
            meta: response.data.meta,
            data: response.data.data,
            loading: false,

          },
        });
      }
    });
  };
  fetchChart = (params) => {
    const that = this;
    request(`/workstation_historical_data`, {
      method: 'GET',
      params: {
        ...params,
        start_date: this.state.start_date,
        // start_date: '2020-10-10',
        end_date: this.state.end_date,
        workstation_id: this.props.editRecord.id,
        order_direction: 'desc'
      },
    }).then(response => {
      if (response.status === 200) {
        that.setState({
          [`${params.type}_${params.channel}_chart`]: {
            meta: response.data.meta,
            data: response.data.data,
            loading: false,
          },
        });
      }
    });
  };
  handleRangePickerChange = (dateString, type) => {
    const that = this;
    this.setState({
      [type]: dateString,
    }, function () {

    });
  };
  fetHistory = () => {
    this.fetch({
      type: 'device',
      channel: 0,
      page: 1,
      per_page: 20,
    });
    this.fetch({
      type: 'sensor',
      channel: 1,
      page: 1,
      per_page: 20,
    });
  }
  getOption = (i) => {
    let faqian = [];
    let time = [];
    let sensor_0 = JSON.parse(JSON.stringify(this.state[`sensor_${i}_chart`]))
    let sensor_0_reverse = sensor_0.data.reverse()
    console.log('sensor_0_reverse', sensor_0_reverse)
    for (let i = 0; i < sensor_0_reverse.length; i++) {
      if (sensor_0_reverse[i]) {
        time.push(sensor_0_reverse[i].collected_at.slice(5))
        if(this.props.editRecord.imei==='869098041225032'){
          faqian.push((sensor_0_reverse[i].data.value+0.1).toFixed(3))
        }else{
          faqian.push(sensor_0_reverse[i].data.value)
        }

      }
    }
    let option = {
      title: {
        text: `通道${i + 1}液位`,
        textStyle: {
          color: '#ff5190'
        }
      },
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['液位']
      },
      grid: {
        top: '35px',
        left: '3%',
        right: '4%',
        bottom: '4%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: time,
        axisLabel: {
          showMaxLabel: true
        }
      },
      yAxis: {
        type: 'value',
      },
      series: [
        {
          name: '液位',
          type: 'line',
          large: true,
          smooth: true,
          data: faqian,
          lineStyle: {
            width: 5
          },
          itemStyle: {
            normal: {
              label: {
                show: true,
                position: 'top',
                textStyle: {
                  fontSize: 16,
                  color: "#fff"
                },
                formatter: (params) => {
                  if (faqian.length - 1 == params.dataIndex) {
                    return params.value
                  } else {
                    return ""
                  }
                },
              },
            }
          },
        },

      ]
    };
    return option
  }

  upTo = (v, step) => {
    const mod = v % step;

    return mod ? v - mod + step : v;
  }

  render() {
    console.log('render')
    let template = '';
    const that = this;
    return (
      <div style={{marginTop: '-24px'}} style={{minHeight: '400px'}}>
        <Tabs defaultActiveKey="1">
          <TabPane tab="液位曲线" key="1">
            {
              find(this.permissions, { name:'watch_mode' }) &&<Fragment>
                {this.state.isWatch === -1 ?
                  <div onClick={this.openWatch} style={{marginBottom: '10px'}}><Button
                    type={'primary'}>开启监控模式</Button></div>
                  : <Alert message="正处于监控模式" type="info" showIcon/>
                }
              </Fragment>

            }
            <Row>
              <Col span={24} style={{position:'relative'}}>
                <Button style={{position:'absolute',right:'10px',top:'10px',zIndex:'19'}} size={'small'} onClick={()=>{
                  this.setState({HistoryDataModal:true,color:'#ff5190',type:'sensor',channel:1,name:'液位',renderName:'value'})
                }}>历史曲线</Button>
                <ReactEcharts
                  option={this.getOption(1)}
                  style={{height: '500px', width: '100%'}}
                  theme='my_theme'
                />
              </Col>
            </Row>


          </TabPane>
          <TabPane tab="站点完整数据" key="3">
            <div style={{marginLeft: '16px'}}>
              开始时间 : <DatePicker
              value={moment(this.state.start_date)}
              allowClear={false}
              format="YYYY-MM-DD"
              style={{width: 150, marginRight: '10px'}}
              placeholder={'开始日期'}
              onChange={(e, dateString) => this.handleRangePickerChange(dateString, 'start_date')}
            />
              结束时间 : <DatePicker
              allowClear={false}
              value={moment(this.state.end_date)}
              format="YYYY-MM-DD"
              placeholder={'结束日期'}
              style={{width: 150}}
              onChange={(e, dateString) => this.handleRangePickerChange(dateString, 'end_date')}
            />
              <Button type={'primary'} style={{marginLeft: '10px'}} onClick={() => {
                this.fetHistory()
                if (this.timer) {
                  clearInterval(this.timer)
                }
              }}>刷新</Button>
              <Button type={'primary'} style={{marginLeft: '10px'}} onClick={() => {
                this.props.downloadHistory(this.state.start_date, this.state.end_date, this.props.editRecord.id);

              }}>下载当前时间段数据</Button>
            </div>
            <Tabs size={'small'} style={{marginTop: '8px'}} defaultActiveKey="sensor_1">
              {
                this.state.tabPanes.map((item, index) => {
                  let renderTab = '';
                  if (item.key === 'device') {
                    renderTab = <TabPane tab={item.name} key={item.key}>
                      <div>
                        <Table
                          style={{color: '#fff'}}
                          className={`custom-small-table ${this.state[`device_0`].data.length === 0 && 'custom-small-table2'}`}
                          loading={this.state[`device_0`].loading}
                          rowKey={'id'}
                          dataSource={this.state.device_0.data}
                          columns={[
                            {
                              title: '采集时间',
                              dataIndex: 'collected_at',
                              width: 160,
                            },
                            {
                              title: '运行时间',
                              dataIndex: 'uptime',
                              width: 120,
                              render: (text, record) => (
                                timeStamp(record.data.uptime)
                              ),
                            },
                            {
                              title: '重置原因',
                              dataIndex: 'reset_reason',
                              width: 80,
                              render: (text, record) => (
                                record.data.reset_reason
                              ),
                            },
                            {
                              title: <span>供电电压(V)</span>,
                              dataIndex: 'supply_voltage',
                              width: 150,
                              render: (text, record) => (
                                (record.data.supply_voltage / 1000).toFixed(3)),
                            },
                            {
                              title: <span>信号质量(dbm)</span>,
                              dataIndex: 'network_signal_quality',
                              render: (text, record) => (
                                record.data.network_signal_quality
                              ),
                            },
                          ]}
                          pagination={false}
                          size="small"
                          scroll={{x: true, y: 400}}
                        />
                        <MyPagination className="history-pagination" searchCondition={{
                          type: item.key,
                          channel: 0,
                        }} meta={this.state[`${item.key}_0`].meta} handleSearch={this.fetch}/>
                      </div>
                    </TabPane>;
                  }
                  if (item.key === 'sensor_0' || item.key === 'sensor_1' || item.key === 'sensor_2' || item.key === 'sensor_3') {
                    renderTab = <TabPane tab={item.name} key={item.key}>
                      <div>
                        <Table
                          style={{color: '#fff'}}
                          className={`custom-small-table ${this.state[item.key].data.length === 0 && 'custom-small-table2'}`}
                          loading={this.state[item.key].loading}
                          rowKey={'id'}
                          dataSource={this.state[item.key].data}
                          columns={[
                            {
                              title: '采集时间',
                              dataIndex: 'collected_at',
                              width: 160,
                            },
                            {
                              title: '液位',
                              dataIndex: 'value',
                              render: (text, record) => {
                                if(this.props.editRecord.imei==='869098041225032'){
                                  return (record.data.value+0.1).toFixed(3)
                                }else{
                                  return record.data.value
                                }
                              }
                            },
                          ]}
                          pagination={false}
                          size="small"
                          scroll={{x: true, y: 405}}
                        />
                        <MyPagination className="history-pagination" searchCondition={{
                          type: 'sensor',
                          channel: item.key === 'sensor_0' ? 0 : 1,
                        }} meta={this.state[item.key].meta} handleSearch={this.fetch}/>
                      </div>
                    </TabPane>;
                  }

                  return renderTab;
                })
              }
            </Tabs>

          </TabPane>
        </Tabs>

        <Modal
          title={<BuildModalTitle visible={this.state.HistoryDataModal} modalClass="HistoryDataModal"
                                  title={`${this.props.name} 历史数据`}/>}
          destroyOnClose
          onCancel={() => {
            this.setState({
              HistoryDataModal: false,
            });
          }}
          width={1100}
          centered
          className="HistoryDataModal"
          afterClose={() => {
            afterCloseModal(); // destroyOnClose需要
          }}
          visible={this.state.HistoryDataModal}
          footer={null}
        >
          <ValveHistoryData name={this.state.name}
                            renderName={this.state.renderName}
                            color={this.state.color}
                            type={this.state.type}
                            remark={0.1}
                            channel={this.state.channel}
                            workstation_id={this.props.editRecord.id}/>
        </Modal>
      </div>

    );
  }
}

const AddPoliciesFormWrap = Form.create()(AddPoliciesForm);
export default connect()(AddPoliciesFormWrap);
